package cn.yza.线程.异步;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

/** 两任务组合，一个完成,就执行任务3
 *      runAfterEitherAsync():不感知结果，自己也无返回值
 *      acceptEitherAsync():感知结果，无返回值return
 *      applyToEitherAsync():感知结果，有返回值
 * @author Honglixi
 * @create 2021-11-06 16:41
 */
public class Test3 {
    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Object> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1线程" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("任务1完成");
            return i;
        }, executor);
        CompletableFuture<Object> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2线程" + Thread.currentThread().getId());


            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务2完成");
            return "Hello World";

        }, executor);


//        future1.runAfterEitherAsync(future2,() -> {
//            System.out.println("任务3开始");
//        },executor);

////        void accept(T t); 传一个参数进来，可返回
//        future1.acceptEitherAsync(future2,(res) -> {
//            System.out.println("任务3开始,结果为：" + res);
//        }, executor);
        CompletableFuture<String> future = future1.applyToEitherAsync(future2, (res) -> {

            return "返回结果为："+res.toString() + "哈哈";
        }, executor);
        System.out.println(future.get());

        System.out.println("main线程" );
    }
}
